class SearchController < ApplicationController
  def index
    @body_id = :search
  end
  
  # Search resources based on user's choice
  def search
    # get the search's target
    target = params[:search][:search_item]
    # transforms the target name into a string with the class' name
    class_name = target.singularize.classify
    # get the declared constant of the target class
    class_element = class_name.constantize
    
    search_type = params[:search][:search_type]

    @resources = nil
    @resources = class_element.search(params[:search][:keys]) if search_type == 'normal'
    @resources = class_element.find_by_tags(params[:search][:keys]) if search_type == 'on_tags'
    
    #renders search results, in the _list partial of the target class
    respond_to do |format|
      format.html {
        render :partial => (target + '/list'), :locals => { target.to_sym => @resources, 
          :title => search_title(class_name.titleize. pluralize, @resources) }
      }
      format.xml { render :xml => @resources.to_xml }
    end
  end
  
  private
  def search_title(title, resources)
    "<span class='results_title'>#{title} returned: #{resources.size}</span>"
  end
end